import dotenv from 'dotenv'
import express, {type Request, Response} from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import { createBrowser } from './module/createBrowser.js'
import { router } from "./api/api.js";
import {type Base} from './response/response.js'

const app = express()

async function init() {
    dotenv.config()

    async function initBrowser() {
        let browser = await createBrowser();
        browser.on('disconnected', () => {
            global.browser = undefined
            setTimeout(initBrowser, 3000)
            console.log('Browser disconnected');
        })
        global.browser = browser
    }
    await initBrowser();

    app.use(bodyParser.json({}))
    app.use(bodyParser.urlencoded({ extended: true }))
    app.use(cors())
    router(app)
    app.use((_ :Request, res :Response) => {
        const resp: Base<null> = { code: 404, msg: 'Not Found', data: null}
        res.status(404).json(resp)
    })
    global.maxConcurrency = 128;
}

async function main() {
    const port = Number(process.env.PORT) || 3000;
    app.listen(port, () => {
        console.log(`Server running on port ${port}`)
    })
}

await init()
await main()
